<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <!-- 引用公共依赖片段（Vue + Element Plus + Axios） -->
    <th:block th:replace="common/head-fragment :: common-head"></th:block>
</head>
<body>
<div class="container">
    <div id="app" th:inline="javascript">
        <div>
            <el-input v-model="input" style="width: 240px" placeholder="Please input"/>
        </div>
        <!--<el-upload
                class="avatar-uploader"
                action="/image/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
        >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
            </el-icon>
        </el-upload>-->
        <!-- 只保留上传组件 -->
        <div>
            <el-upload
                    class="avatar-uploader"
                    action="/image/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :on-change="handleFileChange"
            >
                <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus/>
                </el-icon>
            </el-upload>
        </div>
        <div class="button-example">
            <div class="button-row">
                <el-button type="primary" @click="submitImage">提交</el-button>
            </div>
        </div>
    </div>
</div>
<script>
    // 5.1 从全局 Vue 中获取所需 API
    const {createApp, ref} = Vue;
    // Element Plus 组件和图标
    const {ElMessage} = ElementPlus;
    const {Plus} = ElementPlusIconsVue;

    // 5.3 创建 Vue 实例
    createApp({
        components: {
            ElUpload: ElementPlus.ElUpload,
            ElIcon: ElementPlus.ElIcon,
            Plus: Plus
        },

        setup() {
            // 上传成功回调
            const handleAvatarSuccess = (response) => {
                if (response.code === 200 && response.data?.url) {
                    console.log(response.data.url);
                    saveImageUrl.value = response.data.url; // 显示服务器返回的图片
                    ElMessage.success('上传成功！');
                } else {
                    ElMessage.error('上传失败：' + (response.msg || '未知错误'));
                }
            }
            // 新增：文件选择后立即转换为 base64 预览
            const handleFileChange = (file) => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    // 先临时显示本地预览（不依赖服务器返回的路径）
                    imageUrl.value = e.target.result;
                };
                // 读取选中的文件并转换为 base64
                reader.readAsDataURL(file.raw);
            };
            // 上传前校验
            const beforeAvatarUpload = (rawFile) => {
                const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
                if (!isJPG) {
                    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
                    return false;
                }
/*                const isLt2M = rawFile.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    ElMessage.error('上传头像图片大小不能超过 2MB!');
                    return false;
                }*/
                return true;
            }
            // 提交图片到后端
            const submitImage = () => {
                if (!imageUrl.value) {
                    ElMessage.error('请先上传图片！');
                    return;
                }
                if (!input.value) {
                    ElMessage.error('请输入图片描述！');
                    return;
                }
                // 发送 POST 请求到后端
                axios.post('/image/saveImage', {
                    imageUrl: saveImageUrl.value,
                    imageName:input.value
                }).then(response => {
                    if (response.data.code === 200) {
                        ElMessage.success('图片上传成功！');
                        // 清空上传路径
                        imageUrl.value = '';
                        saveImageUrl.value = '';
                    } else {
                        ElMessage.error('图片上传失败：' + (response.data.msg || '未知错误'));
                    }
                }).catch(error => {
                    ElMessage.error('图片上传失败：' + error.message);
                });
            }
            // 5.4 响应式变量（控制弹窗显示 + 本地页面路径）
            const input = ref(''); // 初始隐藏弹窗
            const imageUrl = ref('');
            const saveImageUrl = ref('');
            return {
                input,
                imageUrl,
                saveImageUrl,
                handleAvatarSuccess,
                beforeAvatarUpload,
                submitImage,
                handleFileChange
            };
        }
    })
        .use(ElementPlus) // 5.6 注册 Element Plus 组件
        .mount('#app');
</script>

<style>
    /* 合并所有样式，确保生效 */
    .avatar-uploader {
        display: inline-block;
    }

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
        border-radius: 6px;
    }

    .avatar-uploader .el-upload {
        width: 178px;
        height: 178px;
        border: 1px dashed #dcdfe6;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    .avatar-uploader-icon {
        width: 100%;
        height: 100%;
        line-height: 178px;
        font-size: 28px;
        color: #666;
    }

    .avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
</style>
</body>
</html>